{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '2'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate,\n",
    "                beam_width = 5):\n",
    "        \n",
    "        def cell(size, residual, reuse=False):\n",
    "            c = tf.nn.rnn_cell.GRUCell(size,reuse=reuse)\n",
    "            if residual:\n",
    "                c = tf.nn.rnn_cell.ResidualWrapper(c)\n",
    "            return c\n",
    "        \n",
    "        def cells(size = size_layer, residual = 1, reuse=False):\n",
    "            cell_list = []\n",
    "            for i in range(num_layers):\n",
    "                cell_list.append(cell(size, i >= residual, reuse=reuse))\n",
    "            return cell_list\n",
    "        \n",
    "        def attention(encoder_out, seq_len, reuse=False):\n",
    "            attention_mechanism = tf.contrib.seq2seq.LuongAttention(num_units = size_layer, \n",
    "                                                                    memory = encoder_out,\n",
    "                                                                    memory_sequence_length = seq_len)\n",
    "            return tf.contrib.seq2seq.AttentionWrapper(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell(cells(reuse=reuse)), \n",
    "                attention_mechanism = attention_mechanism,\n",
    "                attention_layer_size = size_layer)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        \n",
    "        encoder_out, encoder_state = tf.nn.dynamic_rnn(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell(cells()), \n",
    "            inputs = tf.nn.embedding_lookup(embeddings, self.X),\n",
    "            sequence_length = self.X_seq_len,\n",
    "            dtype = tf.float32)\n",
    "        main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        dense = tf.layers.Dense(vocab_size)\n",
    "        decoder_cells = attention(encoder_out, self.X_seq_len)\n",
    "        \n",
    "        states = decoder_cells.zero_state(batch_size, tf.float32).clone(cell_state=encoder_state)\n",
    "        \n",
    "        training_helper = tf.contrib.seq2seq.TrainingHelper(\n",
    "                inputs = tf.nn.embedding_lookup(embeddings, decoder_input),\n",
    "                sequence_length = self.Y_seq_len,\n",
    "                time_major = False)\n",
    "        training_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                cell = decoder_cells,\n",
    "                helper = training_helper,\n",
    "                initial_state = states,\n",
    "                output_layer = dense)\n",
    "        training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = training_decoder,\n",
    "                impute_finished = True,\n",
    "                maximum_iterations = tf.reduce_max(self.Y_seq_len))\n",
    "        self.training_logits = training_decoder_output.rnn_output\n",
    "        \n",
    "        predicting_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(\n",
    "                embedding = embeddings,\n",
    "                start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n",
    "                end_token = EOS)\n",
    "        predicting_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                cell = decoder_cells,\n",
    "                helper = predicting_helper,\n",
    "                initial_state = states,\n",
    "                output_layer = dense)\n",
    "        predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = predicting_decoder,\n",
    "                impute_finished = True,\n",
    "                maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n",
    "        self.fast_result = predicting_decoder_output.sample_id\n",
    "        \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-8-898355b1b03f>:12: GRUCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.GRUCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-8-898355b1b03f>:42: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-8-898355b1b03f>:45: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:559: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:565: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:575: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[   37, 13009, 13009, 12879,  6839,  7171,  7171,  7171,  7171,\n",
       "          7171,  7171,  7171, 21304, 22121,    37,    37,    37, 27938,\n",
       "         27938, 27938, 28560, 28560, 28560, 28560, 29665,  4627, 26103,\n",
       "         26103, 23145, 21377,  1881,  1881,  1881, 13215, 26103, 19720,\n",
       "         26103, 16690, 17704, 12269, 12269, 12269, 31881, 31881, 31881,\n",
       "          5813,  5813,  8109,  8109,  2338,  2375,  2375,  2375,  3312,\n",
       "         15435,  9656, 15435,  9656, 30516, 19282, 19282,  1878,  1878,\n",
       "         22523,   647, 19239, 29303,   647, 19384, 19384, 19384, 13459],\n",
       "        [27556,   557,  5648,  5648, 14805,   496,  3022,  3022, 11803,\n",
       "         11803, 20709, 31037, 31037,  8552, 11767, 11767, 11767, 31806,\n",
       "         31806,  6223,  3358,  4836,  3358,  4836,  1348, 27445, 27445,\n",
       "         27445, 10765,  7656,  7656,  6202,  1315, 19911, 19911, 19911,\n",
       "          3023, 19911,  1494,  2802, 29319, 12890, 17652,  2802, 20040,\n",
       "         18043, 26183, 26183, 26183, 24737, 24737, 19702, 19702, 21633,\n",
       "          3683, 19702,  6268, 23809,  6268,  6268,  6268, 23328,  6268,\n",
       "          6268,  6268, 23328,  6268,  6268, 23328,  6268,  6268, 23328],\n",
       "        [11697, 25656, 19509, 19509,  8367,  8367, 21622, 24611, 25656,\n",
       "         11596, 31850, 31850,  5482, 31850, 29281,  5558,  5558, 30875,\n",
       "         20055, 31850, 21962, 21962,  9374, 25681, 19029,  9690, 29405,\n",
       "          3850, 27872, 27872, 27872, 27872, 23887,  5558,  5558,  2304,\n",
       "          2304,  2304, 27872,  1052,   221,   221,   221, 25748, 17863,\n",
       "         17863, 17863, 14477, 23687, 24772, 24772, 21531, 23703,  1542,\n",
       "          1542, 13161,  8669,  1542,  1542, 10474, 29642,   345, 16359,\n",
       "         16359,  1542, 20547,  4430,  4430,  4430,  9344,  5482,  5482],\n",
       "        [21394, 27593,  5956, 20801, 20801,  1121,  2000,  2000,  2000,\n",
       "         30541,  6713,  6713,  6713,  6713,  6713,  6713,  6713,  6713,\n",
       "         20237, 22015, 22015,  6713,  6713,  6713,  6713, 19347,  7776,\n",
       "         20828, 20828, 20828, 20828, 29983, 31758, 31758, 31758, 28447,\n",
       "          8159,  8159,  8159,  8159,  8159,  8159,  8159,  2084,  4387,\n",
       "          4387, 22845,  8159,  2084,  8159,  8159,  2084,  8159,  2084,\n",
       "          8159,  2084,  8159, 18880,  4083,  4083,  4083,  4083,  4083,\n",
       "          4083,  4083, 11567,  4083, 22687, 13735, 13735, 30318, 13735],\n",
       "        [15273, 22242, 23385, 11381,   422,  4382,  4382, 17712, 17712,\n",
       "         23275, 27700, 28845, 28845, 14008,  3213,  3213, 18995, 18995,\n",
       "         22317, 26495, 26495,  8489,  8489, 28745, 26744,  4815, 28186,\n",
       "         28186, 12297,  4936,  4936,  4936, 18040, 16508,   472, 18842,\n",
       "          4633, 11943, 11943, 26941, 26941,  2017,  2017,  2017,  2017,\n",
       "          2017,  2017,  2017, 14846, 14846, 14846, 18842, 18842, 12763,\n",
       "         12763, 12763, 28419, 12763, 12763, 28419, 12763,  9243,  3505,\n",
       "         31169, 31169, 31169, 31169, 31169, 31169, 14671, 12700,  8610],\n",
       "        [24520, 29348, 11931, 21709, 31484, 26354, 31484, 29565,  3070,\n",
       "         29429, 28766, 30589,  1668,  1668,  1668,  1668,  1668, 25289,\n",
       "         25289, 17613, 25289,  5147,  3685,  3685, 25155,  5988,  5988,\n",
       "          5988, 26992, 26992, 17186,  5988, 26992, 26992,  6181,  6181,\n",
       "          6181,  6181, 14493,  6181, 14493,  1777,  4146,  1777,  6406,\n",
       "          6406, 25359, 25359, 25359,  4540,  7274, 19845, 25359, 25359,\n",
       "          7274, 22866, 22866, 13361, 24435, 30348,  3604,  3604, 14427,\n",
       "         22634,  3004, 22634,  3004,  3007,  6635,  5363,  3004,  3007],\n",
       "        [ 2951,  7098,  1964, 27086, 27086,   675, 18800,  6107, 22157,\n",
       "         22157, 30604, 18097,  7059, 21811, 21811, 29265, 29265, 15823,\n",
       "          8211,  8211, 13208, 13208, 13208, 13208, 11948, 28970, 19054,\n",
       "         21811,  6703,  9544, 13663, 16477, 31445, 16477, 30985, 15766,\n",
       "         15766, 19407, 30731, 30731, 30731, 25434, 25434, 25434, 25434,\n",
       "         25434, 25434, 25434, 25434,  1793, 10750, 18029, 14655, 14655,\n",
       "         10200, 13825, 13825, 25780,  6119, 11249,  7245, 19647, 19647,\n",
       "         11249, 30859, 30859, 30859, 27677, 23058, 18222, 15269, 15269],\n",
       "        [20258,  8702, 10705, 10705, 18800,  4373, 21454,  5557,  1435,\n",
       "          7948, 17996,   439, 25223, 10016, 28819, 18599, 26296, 22377,\n",
       "         22377, 15721, 31291, 31291, 31291, 28054, 17321,  4735,  8799,\n",
       "          3162, 14570, 12965,  5183,  5464, 17094,  5183, 17094,  2182,\n",
       "          2182,  2182,  2182,     9,  7679,  7679, 28177, 25344, 14900,\n",
       "         25344, 14900, 14900, 30556, 30556, 30556, 30556, 17174, 25946,\n",
       "         25946,  2234, 25946, 23096, 22227, 22227, 22227, 22227, 15448,\n",
       "         15448, 15448,  8448,  8448,  8448,  8448,  8448,  8448,  8448],\n",
       "        [ 9717,  9717,  6382, 11767, 11767, 10670, 10296,  2939,  5557,\n",
       "         26899,  5557,  1435, 11767, 11767, 11767,  3009,  9416,  9416,\n",
       "         19831, 31637, 29692, 21637, 29692,  6382, 29692, 29692, 21637,\n",
       "         18158, 29692, 21637, 18158, 29692, 29692, 20742, 31866, 29692,\n",
       "         29692, 21637, 12486, 23847, 29751,  4401,  5482, 22170, 12486,\n",
       "          6683,  5482, 30940, 30940, 25510, 25510,   525, 25510, 19912,\n",
       "         21604,  6683, 21604,  6683,  3213,  3213,  3213,  1702,  1702,\n",
       "          1702,  1702, 19491,  1702, 19491, 30525, 30525,  6892,  5167],\n",
       "        [31012, 23454, 23454, 15517, 16873, 15577, 29436,   502,  1869,\n",
       "         31404, 11958, 11958, 31588, 30280, 14949, 17377, 30280, 30280,\n",
       "         14949, 10317, 17377, 24187, 30280, 30280, 25336, 25336, 25336,\n",
       "         25336, 24683,  9149,  9149,  9149, 15684, 15684, 29905, 29905,\n",
       "         31837, 28415, 19309, 21314, 21314, 25681, 25681, 26914, 26914,\n",
       "         29905, 12774, 12774, 12774, 12774, 17244, 12774, 17244, 27028,\n",
       "         27028,  7959,  5234,  7657,  7571,   617,  7571, 25114,  6202,\n",
       "         10941,  6202,   305,  4521, 27234, 13101,  4521, 10581, 10581]],\n",
       "       dtype=int32), 10.372574, 0.0]"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:44<00:00,  2.43it/s, accuracy=0.296, cost=4.37]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.89it/s, accuracy=0.339, cost=3.72]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 5.107066, training avg acc 0.223867\n",
      "epoch 1, testing avg loss 4.127939, testing avg acc 0.308653\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:43<00:00,  2.43it/s, accuracy=0.398, cost=3.44]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.98it/s, accuracy=0.376, cost=3.42]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 3.767632, training avg acc 0.347137\n",
      "epoch 2, testing avg loss 3.645800, testing avg acc 0.366545\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:43<00:00,  2.43it/s, accuracy=0.422, cost=3.11]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.98it/s, accuracy=0.392, cost=3.36]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 3.366990, training avg acc 0.389415\n",
      "epoch 3, testing avg loss 3.520617, testing avg acc 0.382205\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:43<00:00,  2.43it/s, accuracy=0.453, cost=2.93]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.99it/s, accuracy=0.392, cost=3.42]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 3.218436, training avg acc 0.404148\n",
      "epoch 4, testing avg loss 3.495510, testing avg acc 0.389147\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:39<00:00,  2.44it/s, accuracy=0.449, cost=2.94]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.06it/s, accuracy=0.43, cost=3.26] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 3.074706, training avg acc 0.419973\n",
      "epoch 5, testing avg loss 3.502872, testing avg acc 0.388683\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:42<00:00,  2.43it/s, accuracy=0.132, cost=6.81] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.99it/s, accuracy=0.129, cost=6.58]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 8.812689, training avg acc 0.128621\n",
      "epoch 6, testing avg loss 6.785951, testing avg acc 0.139825\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:43<00:00,  2.43it/s, accuracy=0.122, cost=7.77] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.95it/s, accuracy=0.108, cost=7.31]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 6.141335, training avg acc 0.160984\n",
      "epoch 7, testing avg loss 7.937228, testing avg acc 0.128523\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:40<00:00,  2.44it/s, accuracy=0.0746, cost=9.35]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.98it/s, accuracy=0.0645, cost=9.11]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 12.094375, training avg acc 0.074499\n",
      "epoch 8, testing avg loss 9.949530, testing avg acc 0.077214\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:43<00:00,  2.43it/s, accuracy=0.0929, cost=8.3] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  5.00it/s, accuracy=0.086, cost=7.66] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 8.917791, training avg acc 0.097551\n",
      "epoch 9, testing avg loss 8.922109, testing avg acc 0.094568\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:41<00:00,  2.44it/s, accuracy=0.108, cost=7.92] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.95it/s, accuracy=0.102, cost=7.45] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 8.303866, training avg acc 0.110367\n",
      "epoch 10, testing avg loss 8.599289, testing avg acc 0.105967\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:42<00:00,  2.43it/s, accuracy=0.12, cost=7.64]  \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.99it/s, accuracy=0.0914, cost=7.44]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 8.099864, training avg acc 0.115987\n",
      "epoch 11, testing avg loss 8.320366, testing avg acc 0.111792\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:43<00:00,  2.43it/s, accuracy=0.109, cost=7.51] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.99it/s, accuracy=0.0968, cost=7.33]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 7.835712, training avg acc 0.123138\n",
      "epoch 12, testing avg loss 8.366531, testing avg acc 0.107625\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:43<00:00,  2.43it/s, accuracy=0.0916, cost=7.88]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.95it/s, accuracy=0.118, cost=7.8]  \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 7.785233, training avg acc 0.121693\n",
      "epoch 13, testing avg loss 8.785860, testing avg acc 0.097379\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:42<00:00,  2.43it/s, accuracy=0.0244, cost=49.2]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.03it/s, accuracy=0.0269, cost=49.7]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 8.456898, training avg acc 0.111696\n",
      "epoch 14, testing avg loss 50.123192, testing avg acc 0.021847\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:43<00:00,  2.43it/s, accuracy=0.0387, cost=14]  \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.99it/s, accuracy=0.0538, cost=11.2]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 27.942133, training avg acc 0.033096\n",
      "epoch 15, testing avg loss 15.008861, testing avg acc 0.032816\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:43<00:00,  2.43it/s, accuracy=0.0597, cost=11.3]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.98it/s, accuracy=0.0591, cost=10.9]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 12.540964, training avg acc 0.051392\n",
      "epoch 16, testing avg loss 12.241220, testing avg acc 0.054679\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:43<00:00,  2.43it/s, accuracy=0.0617, cost=10.4]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.99it/s, accuracy=0.0376, cost=9.11]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 11.262809, training avg acc 0.059520\n",
      "epoch 17, testing avg loss 11.309278, testing avg acc 0.056757\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:43<00:00,  2.43it/s, accuracy=0.0651, cost=9.35]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.99it/s, accuracy=0.043, cost=8.81] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 10.212348, training avg acc 0.066435\n",
      "epoch 18, testing avg loss 10.237161, testing avg acc 0.064585\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:42<00:00,  2.43it/s, accuracy=0.0855, cost=8.13]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.99it/s, accuracy=0.086, cost=7.63] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 9.176891, training avg acc 0.080837\n",
      "epoch 19, testing avg loss 9.292258, testing avg acc 0.078303\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [10:43<00:00,  2.43it/s, accuracy=0.036, cost=58.3] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.95it/s, accuracy=0.0215, cost=53.1]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 55.924133, training avg acc 0.051454\n",
      "epoch 20, testing avg loss 61.256298, testing avg acc 0.026086\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [00:31<00:00,  1.27it/s]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5.0574585e-05"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
